import axios from 'axios'
import Cookies from 'js-cookie'
import moment from 'moment'
import { Toast } from '../pages/components/Toast'
//axios 通用配置
let config = {
  // baseURL: ' http://39.104.71.97:7300/mock/5a645b3f629cd919f17a2caf/api',
  // baseURL: 'http://saicyc.vicp.io',
  // baseURL: 'http://172.16.1.39:8080/api',
  baseURL: '//api.61cr.cn/api/',
  timeout: 10000
}
const instance = axios.create(config)
const setHeader = () => {
  let tokenData = Cookies.get('token')
  const tmSummer = new Date(Date.UTC(moment().year(), 6, 30, 0, 0, 0, 0))
  const zoneSo = -1 * tmSummer.getTimezoneOffset();
  const tmWinter = new Date(Date.UTC(moment().year(), 12, 30, 0, 0, 0, 0))
  const zoneWo = -1 * tmWinter.getTimezoneOffset();
  const headers = {
    'token': tokenData,
    zoneSo,
    zoneWo
  }
  return headers
}
// 请求开始加入loading
instance.interceptors.request.use(config => {
  config.headers = setHeader()
  const time = new Date().getTime()
  if (config.params) {
    config.params.timer = time
  } else {
    config.url += '?timer='+time
  }
  return config
}, error => {
  return Promise.reject(error)
})
instance.interceptors.response.use((response) => {
  if (Object.prototype.toString.call(response.data) === '[object Object]') {
      if (response.data.code === 0) {
        const result = response.data.data;
        return Promise.resolve(result);
      } else if (response.data.code === 48001) {
        window.location.href = "/login/"
        return new Promise()
      } else if (response.data.code === 9999) {
        Toast('24小时内只能发送10次验证码', 'toast-top', 'alert-danger', 5000)
      }
  }
  const error = response.data || {};
  error.msg = error.msg || '接口调用失败';
  return Promise.reject(error);
}, (err) => {
  const error = err || {};
  error.msg = error.msg || '接口调用失败';
  if (!err.response) {
    Toast('网络连接异常请重试', 'toast-top', 'alert-danger', 5000)
  } else if (error.response.status >= 500) {
    Toast('网络连接异常请重试', 'toast-top', 'alert-danger', 5000)
  } else if (error.response.status >=400 && error.response.status < 500) {
    Toast('网络连接异常请重试', 'toast-top', 'alert-danger', 5000)
  }
  return Promise.reject(error);
});
export default instance